package com.gitee.feizns.quickstart.web.spring.boot.autoconfigure;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.gitee.feizns.quickstart.domain.vo.Ret;
import com.gitee.feizns.quickstart.upload.FileStorage;
import com.gitee.feizns.quickstart.web.WebUtils;
import com.gitee.feizns.quickstart.web.domain.upload.ao.UploadAo;
import com.gitee.feizns.quickstart.web.domain.upload.vo.UploadVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 * @author feizns
 * @since 2025/2/7
 */
@RestController
public class UploadController {

    /**
     * 文件存储
     */
    @Lazy
    @Autowired
    private FileStorage fileStorage;

    /**
     * 获取 AB URL 域
     * @return {@link String }
     */
    public String baseUrl() {
        return WebUtils.getServerName() + "/static/";
    }

    /**
     * 文件上传
     * @param ao 请求参数
     * @return {@link Object}
     */
    @SneakyThrows
    @ResponseBody
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Ret<UploadVo> create(@Validated UploadAo ao) {
        UploadVo vo = new UploadVo();
        MultipartFile file = ao.getFile();
        //获取源文件扩展名
        String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        //是否使用自定义名称
        String fileKey = computeFileKey(ao.getFileKey(), extension);
        //保存文件
        fileStorage.put(fileKey, ao.getFile().getInputStream());
        vo.setKey(fileKey);
        vo.setExt(extension);
        vo.setFilename(StringUtils.getFilename(fileKey));
        vo.setAbUrl(baseUrl() + fileKey);
        vo.setExtra(ao.getExtra());
        vo.setSize(file.getSize());
        return Ret.ok(vo);
    }

    /**
     * 文件计算
     * @return {@link String}
     */
    private String computeFileKey(String fileKey, String extension) {
        return StringUtils.hasText(fileKey) ? fileKey : NanoIdUtils.randomNanoId() + "." + extension;
    }

}
